//
//  TXFReflesh.swift
//  TXFRefreshControl
//
//  Created by 田侠飞 on 16/7/1.
//  Copyright © 2016年 田侠飞. All rights reserved.
//

import UIKit
let TXFRefleshHeight : CGFloat = 50
let SCREEDNW = UIScreen.mainScreen().bounds.width

enum TXFRefleshType: Int{

    case Normal = 0
    case Pulling = 1
    
    case Refreshing = 2


}

class TXFReflesh: UIControl {
    //被观察者
    var scrollView : UIScrollView?
    
    var refreshState : TXFRefleshType = .Normal{
        didSet{
        
            switch refreshState{
            
            case .Normal:
                
                messageLable.text = "正常"
                
                if oldValue == .Refreshing{
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    self.scrollView?.contentInset.top -= TXFRefleshHeight
                    
                })
                
                }
            case .Pulling:
                
                messageLable.text = "下拉中"
                
                
                
                
                
            case .Refreshing:
                
                messageLable.text = "刷新中"
            
              
           UIView.animateWithDuration(0.25, animations: { () -> Void in
            self.scrollView?.contentInset.top += TXFRefleshHeight
            }, completion: { (_) -> Void in
                 self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
           })
            
        
        }
    
        }
    
   
    }
  override  init(frame: CGRect) {
    super.init(frame: CGRect(x: 0, y: -TXFRefleshHeight , width: SCREEDNW, height: TXFRefleshHeight))
    
    setupUI()
    
    }

  required init?(coder aDecoder: NSCoder) {
      fatalError("init(coder:) has not been implemented")
  }
    
    func  setupUI(){
    backgroundColor = UIColor.orangeColor()
    
    addSubview(messageLable)
        
        
    
    
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        messageLable.frame = CGRect(x: 0, y: 0, width: SCREEDNW, height: TXFRefleshHeight)
        
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        
       
        //使用KVO来监听属性的变化
        
        guard let scrollView = newSuperview as? UIScrollView  else{
        
        
        return
        }
        
        self.scrollView = scrollView
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
        

    }
    
   override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    
    
    let contentOffSetY = self.scrollView?.contentOffset.y
    let contentInsetTop = self.scrollView!.contentInset.top
    
    if scrollView!.dragging  {
    
        if contentOffSetY  > -contentInsetTop - TXFRefleshHeight   && refreshState == .Pulling{
      
          refreshState = .Normal
        
        }else if contentOffSetY <= -contentInsetTop - TXFRefleshHeight  && refreshState == .Normal{
        
        
             refreshState = .Pulling
        }
   
    
    }else{
    
        if refreshState == .Pulling {
        
        refreshState = .Refreshing
        }
    
    }
    
    
    }
    
    func endRefreshuing(){
    refreshState = .Normal
    
    }
    
    
    //懒加载控件
    
    private lazy var messageLable: UILabel = {
    
    let lab = UILabel()
        
        lab.font = UIFont.systemFontOfSize(15)
    
        lab.textAlignment = .Center
        
        lab.text = "正常"
        
        lab.textColor = UIColor.whiteColor()
        return lab
    }()
    
    deinit{
    
    
        self.scrollView?.removeObserver(self, forKeyPath:"contentOffset")
    
    }

}
